package com.example.vue_shop.components.rights.utils;

import com.example.vue_shop.components.rights.entity.Rights;
import com.example.vue_shop.components.rights.entity.TreeRights;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author lipengwei
 */
public class RightsUtils {

    /**
     * 把权限列表转换为树形结构.
     *
     * @param rights 需要转换的权限列表
     */
    public static List<TreeRights> getTreeRights(List<Rights> rights) {
        // 把right转换为TreeRight
        List<TreeRights> treeRightsList = new ArrayList<>();
        rights.forEach(right -> {
            TreeRights treeRights = new TreeRights();
            treeRights.setId(right.getId());
            treeRights.setRightsName(right.getRightsName());
            treeRights.setRightsGrade(right.getRightsGrade());
            treeRights.setPath(right.getPath());
            treeRights.setParentId(right.getParentId());
            treeRights.setCode(right.getCode());
            treeRightsList.add(treeRights);
        });

        HashMap<String, TreeRights> map = new HashMap<>(rights.size());
        treeRightsList.forEach(treeRights -> map.put(treeRights.getCode(),
                treeRights));

        // 返回对象
        List<TreeRights> result = new ArrayList<>();
        // 循环整个权限列表
        treeRightsList.forEach(treeRights -> {
            /* 000000
               010000 一级目录
               010100 二级目录
               010101 三级目录
            code 属性默认为三级，以后可以扩展 前两位为第一级，三四位为二级，
            * 五六位为三级，以此类推。
            * */
            String code = treeRights.getCode();

            /* 先判断 code 4，5 位，如果是00。则为一级目录，否则就是找到其父级对象，
            并且添加进入其子对象， */
            // 判断3，4为 == 00 说明是一级对象，
            if ("00".equals(code.substring(2, 4))) {
                result.add(treeRights);
            } else {
                // 是二级
                TreeRights fatherTreeRights;
                if ("00".equals(code.substring(4, 6))) {
                    String substring = code.substring(0, 2);
                    fatherTreeRights = map.get(substring + "0000");
                } else {
                    // 三级
                    String substring = code.substring(0, 4);
                    fatherTreeRights = map.get(substring + "00");
                }
                String parentName = fatherTreeRights.getRightsName();
                treeRights.setParentName(parentName);
                List<TreeRights> children = fatherTreeRights.getChildren();
                if (children == null) {
                    children = new ArrayList<>();
                }
                if (!children.contains(treeRights)) {
                    children.add(treeRights);
                }
                fatherTreeRights.setChildren(children);
            }
        });
        return result;
    }
}
